package com.wave.wavesystem.serve.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.wave.common.util.Func;
import com.wave.wavesystem.serve.pojo.entity.CurrentUser;
import com.wave.wavesystem.serve.pojo.entity.User;
import com.wave.wavesystem.serve.service.IUserService;
import com.wave.wavesystem.serve.util.CurrentUserUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RequiredArgsConstructor
public class CurrentUserInterceptor implements HandlerInterceptor {

    private final IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean login = StpUtil.isLogin();
        if (login) {
            long id = StpUtil.getLoginIdAsLong();
            User one = userService.queryChain().eq(User::getId, id).one();
            if (Func.isEmpty(one)) {
                return true;
            }
            CurrentUser currentUser = new CurrentUser(one);
            CurrentUserUtil.setCurrentUser(currentUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        CurrentUserUtil.removeCurrentUser();
    }

}
